import { useState } from "react";

import { IfElse } from "../IfElse/IfElse"
import { Checkbox } from "../ui/checkbox";
import { NewChecklist } from "../NewTask/NewChecklist";
import { useAppDispatch } from "@/hook/useRedux";
import { toggleStatusChecklist } from "@/redux/tasks/tasksSlice";
import { TaskCardExecutor } from "./TaskCardExecutor";
import { TaskCardTags } from "./TaskCardTags";
import { ChecklistCardDate } from "./ChecklistCardDate";

interface Props {
  data: Task[];
  taskId: number
  parentId: number
  columnId: number
}

export const SubTaskChecklist = ({ data, taskId, columnId, parentId }: Props) => {
  const [newSubtask, setNewSubtask] = useState(false);

  return (
    <>
      <ul className="ml-4 divide-y " >
        {data?.map(subtask => <CheckBoxListItem key={subtask.id} task={subtask} columnId={columnId} subtaskId={taskId} taskId={parentId} />)}
        <li className="py-1">
          <IfElse>
            <IfElse.When isTrue={newSubtask} >
              <NewChecklist setOpen={setNewSubtask} parentId={taskId} aiShow={false} columnId={columnId.toString()} grandParentId={parentId} />
            </IfElse.When>
          </IfElse>
        </li>
      </ul>
    </>
  )
}

interface Item {
  task: Task;
  taskId: number;
  subtaskId: number;
  columnId: number;
}

const CheckBoxListItem = ({ task, taskId, subtaskId, columnId }: Item) => {
  const [data] = useState(task);
  const dispatch = useAppDispatch()

  const handleRemove = () => {
    // console.log(columnId, grandparentId, parentId, task.id)
  }

  const handleCheckboxClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    const isChecked: 0 | 1 = task.is_closed === 1 ? 0 : 1
    const checkChangeStatus = {
      status: isChecked,
      colId: columnId,
      taskId,
      subtaskId,
      checkId: task.id,
    }
    dispatch(toggleStatusChecklist(checkChangeStatus))
  };

  return <li className="py-2 flex flex-col gap-2 text-sm items-start" key={data.id} onClick={handleRemove} >
    <div className="flex w-full" >
      <Checkbox
        onClick={handleCheckboxClick}
        checked={!!task.is_closed}
        className='size-[18px] rounded-full'
      />
      <div></div>
    </div>
    <TaskCardTags taskData={task} />
    <h3>{data.name}</h3>
    <div>
      <TaskCardExecutor performers={data.performers} />
      <ChecklistCardDate
        subtaskId={subtaskId}
        taskId={taskId}
        checklistId={task.id}
        endDate={task.end_date}
        columnId={columnId}
      />
    </div>
  </li>
}